package com.example.demo.controller;

import com.anlu.session.MyRequestWrapper;
import com.anlu.session.SessionFilter;
import com.anlu.session.UserForm;
import com.anlu.session.utils.CookieBasedSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class IndexController {

    @GetMapping("/toLogin")
    public String toLogin(Model model, MyRequestWrapper request){
        UserForm userForm = new UserForm();
        userForm.setUsername("anlu");
        userForm.setPassword("anlu");
        userForm.setBackurl(request.getParameter("url"));
        model.addAttribute("user", userForm);
        System.out.println("代码3");
        return "login";
    }
    @PostMapping("/login")
    public void login(@ModelAttribute UserForm user, MyRequestWrapper request, HttpServletResponse response) throws IOException {
        request.getSession().setAttribute(SessionFilter.USER_INFO,user);
        //登录成功后 种cookie
        CookieBasedSession.onNewSession(request,response);
        //重定向回原来的url
        response.sendRedirect(user.getBackurl());

    }
    @GetMapping("/index")
    public ModelAndView index(MyRequestWrapper request){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("user",request.getSession().getAttribute(SessionFilter.USER_INFO));
        request.getSession().setAttribute("test","123");
        return modelAndView;
    }

}
